<template>
  <div class="check-plan-settings-container">
    <h2>盘点计划设置</h2>
    
    <el-card class="filter-card">
      <div class="filter-controls">
        <el-select v-model="selectedPlan" placeholder="选择计划" @change="loadPlanSettings">
          <el-option
            v-for="plan in availablePlans"
            :key="plan.id"
            :label="plan.planName"
            :value="plan"
          ></el-option>
        </el-select>
        
        <el-button type="primary" size="small" @click="saveSettings">保存设置</el-button>
        <el-button type="warning" size="small" @click="resetSettings">重置设置</el-button>
        <el-button type="info" size="small" @click="previewSettings">预览设置</el-button>
      </div>
    </el-card>
    
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>基本设置</span>
        </div>
      </template>
      
      <el-form :model="settingsForm" label-width="120px">
        <el-form-item label="盘点计划" prop="planName">
          <el-input v-model="settingsForm.planName" disabled></el-input>
        </el-form-item>
        <el-form-item label="自动生成盘点单号">
          <el-switch v-model="settingsForm.autoGenerateNo" active-text="是" inactive-text="否"></el-switch>
        </el-form-item>
        <el-form-item label="盘点单号前缀">
          <el-input v-model="settingsForm.noPrefix" placeholder="如：CP"></el-input>
        </el-form-item>
        <el-form-item label="盘点时间要求" prop="checkTimeLimit">
          <el-select v-model="settingsForm.checkTimeLimit" placeholder="请选择">
            <el-option label="无限制" value="none"></el-option>
            <el-option label="工作日内" value="workday"></el-option>
            <el-option label="指定时间" value="specific"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" v-if="settingsForm.checkTimeLimit === 'specific'">
          <el-time-picker v-model="settingsForm.startTime" format="HH:mm" placeholder="选择开始时间"></el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间" v-if="settingsForm.checkTimeLimit === 'specific'">
          <el-time-picker v-model="settingsForm.endTime" format="HH:mm" placeholder="选择结束时间"></el-time-picker>
        </el-form-item>
        <el-form-item label="允许修改资产信息">
          <el-switch v-model="settingsForm.allowModifyAsset" active-text="允许" inactive-text="禁止"></el-switch>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>盘点范围设置</span>
        </div>
      </template>
      
      <el-form :model="settingsForm" label-width="120px">
        <el-form-item label="按部门筛选">
          <el-select
            v-model="settingsForm.deptFilters"
            multiple
            collapse-tags
            placeholder="选择部门"
          >
            <el-option label="IT部门" value="IT部门"></el-option>
            <el-option label="财务部" value="财务部"></el-option>
            <el-option label="人力资源部" value="人力资源部"></el-option>
            <el-option label="市场部" value="市场部"></el-option>
            <el-option label="行政部" value="行政部"></el-option>
            <el-option label="研发部" value="研发部"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="按资产类型筛选">
          <el-select
            v-model="settingsForm.assetTypeFilters"
            multiple
            collapse-tags
            placeholder="选择资产类型"
          >
            <el-option label="电子设备" value="电子设备"></el-option>
            <el-option label="办公家具" value="办公家具"></el-option>
            <el-option label="生产设备" value="生产设备"></el-option>
            <el-option label="车辆" value="车辆"></el-option>
            <el-option label="无形资产" value="无形资产"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="按资产状态筛选">
          <el-select
            v-model="settingsForm.assetStatusFilters"
            multiple
            collapse-tags
            placeholder="选择资产状态"
          >
            <el-option label="在用" value="in_use"></el-option>
            <el-option label="闲置" value="idle"></el-option>
            <el-option label="维修" value="repair"></el-option>
            <el-option label="报废" value="scrapped"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="按存放位置筛选">
          <el-input v-model="settingsForm.locationFilter" placeholder="输入存放位置关键词"></el-input>
        </el-form-item>
        <el-form-item label="资产价值范围">
          <el-input-number
            v-model="settingsForm.minValue"
            placeholder="最小值"
            :min="0"
            style="width: 150px; margin-right: 10px;"
          ></el-input-number>
          <span>至</span>
          <el-input-number
            v-model="settingsForm.maxValue"
            placeholder="最大值"
            :min="0"
            style="width: 150px; margin-left: 10px;"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="资产编号范围">
          <el-input
            v-model="settingsForm.assetNoRange.start"
            placeholder="起始编号"
            style="width: 150px; margin-right: 10px;"
          ></el-input>
          <span>至</span>
          <el-input
            v-model="settingsForm.assetNoRange.end"
            placeholder="结束编号"
            style="width: 150px; margin-left: 10px;"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>盘点人员设置</span>
        </div>
      </template>
      
      <el-form :model="settingsForm" label-width="120px">
        <el-form-item label="分配方式">
          <el-radio-group v-model="settingsForm.assignMethod">
            <el-radio label="按部门分配">按部门分配</el-radio>
            <el-radio label="手动分配">手动分配</el-radio>
            <el-radio label="混合模式">混合模式</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="盘点责任人" v-if="settingsForm.assignMethod !== '按部门分配'">
          <el-select
            v-model="settingsForm.checkUsers"
            multiple
            collapse-tags
            placeholder="选择盘点人员"
          >
            <el-option label="张三" value="zhangsan"></el-option>
            <el-option label="李四" value="lisi"></el-option>
            <el-option label="王五" value="wangwu"></el-option>
            <el-option label="赵六" value="zhaoliu"></el-option>
            <el-option label="钱七" value="qianqi"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门-人员映射" v-if="settingsForm.assignMethod === '按部门分配' || settingsForm.assignMethod === '混合模式'">
          <el-table
            :data="settingsForm.deptUserMapping"
            style="width: 100%"
            border
          >
            <el-table-column prop="dept" label="部门" width="120"></el-table-column>
            <el-table-column prop="users" label="盘点人员">
              <template #default="scope">
                <el-select
                  v-model="scope.row.users"
                  multiple
                  collapse-tags
                  placeholder="选择人员"
                >
                  <el-option label="张三" value="zhangsan"></el-option>
                  <el-option label="李四" value="lisi"></el-option>
                  <el-option label="王五" value="wangwu"></el-option>
                  <el-option label="赵六" value="zhaoliu"></el-option>
                  <el-option label="钱七" value="qianqi"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeDeptUserMapping(scope.$index)"
                  v-if="settingsForm.deptUserMapping.length > 1"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" size="small" @click="addDeptUserMapping">添加映射</el-button>
        </el-form-item>
        <el-form-item label="允许多人盘点同一资产">
          <el-switch v-model="settingsForm.allowMultiUser" active-text="允许" inactive-text="禁止"></el-switch>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>差异处理设置</span>
        </div>
      </template>
      
      <el-form :model="settingsForm" label-width="120px">
        <el-form-item label="自动处理差异">
          <el-switch v-model="settingsForm.autoProcessDiff" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
        <el-form-item label="差异处理方式" v-if="settingsForm.autoProcessDiff">
          <el-radio-group v-model="settingsForm.diffProcessMethod">
            <el-radio label="标记待处理">标记待处理</el-radio>
            <el-radio label="自动调整">自动调整</el-radio>
            <el-radio label="通知管理员">通知管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="差异阈值设置">
          <el-input-number
            v-model="settingsForm.diffThreshold"
            placeholder="差异阈值"
            :min="0"
            :step="1"
            style="width: 200px;"
          ></el-input-number>
          <span style="margin-left: 10px;">（差异数量不超过此值时自动处理）</span>
        </el-form-item>
        <el-form-item label="差异审批流程">
          <el-select v-model="settingsForm.approvalFlow" placeholder="选择审批流程">
            <el-option label="无需审批" value="none"></el-option>
            <el-option label="部门经理审批" value="dept_manager"></el-option>
            <el-option label="财务审批" value="finance"></el-option>
            <el-option label="多级审批" value="multi_level"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="差异原因选项">
          <el-tag
            v-for="(tag, index) in settingsForm.diffReasons"
            :key="index"
            closable
            :disable-transitions="false"
            @close="handleCloseReason(index)"
            style="margin-right: 10px; margin-bottom: 10px;"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="settingsForm.inputVisible"
            v-model="settingsForm.inputValue"
            ref="saveTagInput"
            size="small"
            style="width: 180px;"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          ></el-input>
          <el-button
            v-else
            type="primary"
            icon="Plus"
            size="small"
            @click="showInput"
          >
            添加原因
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>报表与通知设置</span>
        </div>
      </template>
      
      <el-form :model="settingsForm" label-width="120px">
        <el-form-item label="生成盘点报表">
          <el-switch v-model="settingsForm.generateReport" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
        <el-form-item label="报表类型" v-if="settingsForm.generateReport">
          <el-checkbox-group v-model="settingsForm.reportTypes">
            <el-checkbox label="盘点汇总表">盘点汇总表</el-checkbox>
            <el-checkbox label="资产明细表">资产明细表</el-checkbox>
            <el-checkbox label="差异汇总表">差异汇总表</el-checkbox>
            <el-checkbox label="部门对比表">部门对比表</el-checkbox>
            <el-checkbox label="图形化报表">图形化报表</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="自动发送通知">
          <el-switch v-model="settingsForm.autoSendNotice" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
        <el-form-item label="通知方式" v-if="settingsForm.autoSendNotice">
          <el-checkbox-group v-model="settingsForm.noticeMethods">
            <el-checkbox label="系统消息">系统消息</el-checkbox>
            <el-checkbox label="邮件通知">邮件通知</el-checkbox>
            <el-checkbox label="短信通知">短信通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="通知触发事件" v-if="settingsForm.autoSendNotice">
          <el-checkbox-group v-model="settingsForm.noticeEvents">
            <el-checkbox label="计划开始">计划开始</el-checkbox>
            <el-checkbox label="计划提醒">计划提醒</el-checkbox>
            <el-checkbox label="计划结束">计划结束</el-checkbox>
            <el-checkbox label="产生差异">产生差异</el-checkbox>
            <el-checkbox label="审批通知">审批通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="计划提醒时间" v-if="settingsForm.autoSendNotice && settingsForm.noticeEvents.includes('计划提醒')">
          <el-select v-model="settingsForm.remindDays" placeholder="提前几天提醒">
            <el-option label="提前1天" :value="1"></el-option>
            <el-option label="提前3天" :value="3"></el-option>
            <el-option label="提前7天" :value="7"></el-option>
            <el-option label="每天提醒" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import axios from 'axios'

export default {
  name: 'CheckPlanSettings',
  setup() {
    const selectedPlan = ref(null)
    const availablePlans = ref([])
    
    // 表单数据
    const settingsForm = reactive({
      // 基本设置
      planName: '',
      autoGenerateNo: true,
      noPrefix: 'CP',
      checkTimeLimit: 'none',
      startTime: '',
      endTime: '',
      allowModifyAsset: false,
      
      // 盘点范围设置
      deptFilters: [],
      assetTypeFilters: [],
      assetStatusFilters: [],
      locationFilter: '',
      minValue: 0,
      maxValue: 0,
      assetNoRange: {
        start: '',
        end: ''
      },
      
      // 盘点人员设置
      assignMethod: '按部门分配',
      checkUsers: [],
      deptUserMapping: [
        { dept: 'IT部门', users: ['zhangsan'] },
        { dept: '财务部', users: ['lisi'] },
        { dept: '人力资源部', users: ['wangwu'] }
      ],
      allowMultiUser: false,
      
      // 差异处理设置
      autoProcessDiff: false,
      diffProcessMethod: '标记待处理',
      diffThreshold: 5,
      approvalFlow: 'none',
      diffReasons: ['位置变动', '状态变更', '丢失', '损坏', '其他'],
      inputVisible: false,
      inputValue: '',
      
      // 报表与通知设置
      generateReport: true,
      reportTypes: ['盘点汇总表', '资产明细表', '差异汇总表'],
      autoSendNotice: true,
      noticeMethods: ['系统消息'],
      noticeEvents: ['计划开始', '计划提醒', '计划结束'],
      remindDays: 3
    })
    
    // 加载可用的盘点计划
    const loadAvailablePlans = async () => {
      try {
        const response = await axios.get('/api/check/plans')
        if (response.code === 200 && response.data) {
          availablePlans.value = response.data
          if (availablePlans.value.length > 0) {
            selectedPlan.value = availablePlans.value[0]
            loadPlanSettings()
          }
        } else {
          // 使用模拟数据
          setMockPlans()
        }
      } catch (error) {
        console.error('获取盘点计划列表失败:', error)
        setMockPlans()
      }
    }
    
    // 设置模拟计划数据
    const setMockPlans = () => {
      availablePlans.value = [
        {
          id: 1,
          planName: '2024年11月月度盘点',
          status: 'pending'
        },
        {
          id: 2,
          planName: '2024年第四季度盘点',
          status: 'pending'
        },
        {
          id: 3,
          planName: 'IT部门专项盘点',
          status: 'pending'
        }
      ]
      
      if (availablePlans.value.length > 0) {
        selectedPlan.value = availablePlans.value[0]
        loadPlanSettings()
      }
    }
    
    // 加载计划设置
    const loadPlanSettings = async () => {
      if (!selectedPlan.value) return
      
      try {
        const response = await axios.get(`/api/check/plan-settings/${selectedPlan.value.id}`)
        
        if (response.code === 200 && response.data) {
          // 合并设置数据
          Object.assign(settingsForm, response.data)
        } else {
          // 使用默认设置并更新计划名称
          settingsForm.planName = selectedPlan.value.planName
        }
      } catch (error) {
        console.error('获取计划设置失败:', error)
        // 使用默认设置并更新计划名称
        settingsForm.planName = selectedPlan.value.planName
      }
    }
    
    // 保存设置
    const saveSettings = async () => {
      if (!selectedPlan.value) {
        ElMessage.warning('请选择盘点计划')
        return
      }
      
      try {
        const response = await axios.post('/api/check/plan-settings', {
          planId: selectedPlan.value.id,
          settings: settingsForm
        })
        
        console.log('保存设置:', settingsForm)
        ElMessage.success('设置保存成功')
      } catch (error) {
        console.error('保存设置失败:', error)
        ElMessage.error('设置保存失败')
      }
    }
    
    // 重置设置
    const resetSettings = () => {
      ElMessageBox.confirm('确定要重置所有设置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 重置为默认设置
        Object.assign(settingsForm, {
          // 基本设置
          planName: selectedPlan.value ? selectedPlan.value.planName : '',
          autoGenerateNo: true,
          noPrefix: 'CP',
          checkTimeLimit: 'none',
          startTime: '',
          endTime: '',
          allowModifyAsset: false,
          
          // 盘点范围设置
          deptFilters: [],
          assetTypeFilters: [],
          assetStatusFilters: [],
          locationFilter: '',
          minValue: 0,
          maxValue: 0,
          assetNoRange: {
            start: '',
            end: ''
          },
          
          // 盘点人员设置
          assignMethod: '按部门分配',
          checkUsers: [],
          deptUserMapping: [
            { dept: 'IT部门', users: ['zhangsan'] },
            { dept: '财务部', users: ['lisi'] }
          ],
          allowMultiUser: false,
          
          // 差异处理设置
          autoProcessDiff: false,
          diffProcessMethod: '标记待处理',
          diffThreshold: 5,
          approvalFlow: 'none',
          diffReasons: ['位置变动', '状态变更', '丢失', '损坏', '其他'],
          inputVisible: false,
          inputValue: '',
          
          // 报表与通知设置
          generateReport: true,
          reportTypes: ['盘点汇总表', '资产明细表', '差异汇总表'],
          autoSendNotice: true,
          noticeMethods: ['系统消息'],
          noticeEvents: ['计划开始', '计划提醒', '计划结束'],
          remindDays: 3
        })
        
        ElMessage.success('设置已重置')
      }).catch(() => {})
    }
    
    // 预览设置
    const previewSettings = () => {
      ElMessage.info('设置预览功能开发中')
    }
    
    // 添加部门-人员映射
    const addDeptUserMapping = () => {
      settingsForm.deptUserMapping.push({
        dept: '',
        users: []
      })
    }
    
    // 删除部门-人员映射
    const removeDeptUserMapping = (index) => {
      settingsForm.deptUserMapping.splice(index, 1)
    }
    
    // 显示添加原因输入框
    const showInput = () => {
      settingsForm.inputVisible = true
      nextTick(() => {
        const input = document.querySelector('.el-input__inner')
        if (input) {
          input.focus()
        }
      })
    }
    
    // 处理输入框确认
    const handleInputConfirm = () => {
      const inputValue = settingsForm.inputValue.trim()
      if (inputValue && settingsForm.diffReasons.indexOf(inputValue) === -1) {
        settingsForm.diffReasons.push(inputValue)
      }
      settingsForm.inputVisible = false
      settingsForm.inputValue = ''
    }
    
    // 关闭原因标签
    const handleCloseReason = (index) => {
      settingsForm.diffReasons.splice(index, 1)
    }
    
    onMounted(() => {
      loadAvailablePlans()
    })
    
    return {
      selectedPlan,
      availablePlans,
      settingsForm,
      loadPlanSettings,
      saveSettings,
      resetSettings,
      previewSettings,
      addDeptUserMapping,
      removeDeptUserMapping,
      showInput,
      handleInputConfirm,
      handleCloseReason
    }
  }
}
</script>

<style scoped>
.check-plan-settings-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-controls {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-controls .el-select {
  width: 250px;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__content {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.el-form-item__content .el-switch {
  margin-left: 0;
}

.el-form-item__content .el-time-picker {
  width: 150px;
}
</style>